package bs.jizhang.controller;


import bs.jizhang.model.User;
import bs.jizhang.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserRepository Repository;
    public UserController(UserRepository Repository) {
        this.Repository = Repository;
    }


    // 获取列表（支持分页和排序）
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id,asc") String sort) {
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        // 解析排序参数
        String[] sortParams = sort.split(",");
        Sort.Direction direction = Sort.Direction.fromString(sortParams[1]);
        Sort sortBy = Sort.by(direction, sortParams[0]);

        // 创建分页对象
        Pageable pageable = PageRequest.of(page, size, sortBy);

        // 查询分页数据
        Page<User> res = Repository.findAll(pageable);

        // 构建响应
        data.put("list", res.getContent());
        data.put("totalElements", res.getTotalElements());
        data.put("totalPages", res.getTotalPages());
        data.put("currentPage", res.getNumber());
        data.put("pageSize", res.getSize());
        data.put("hasNextPage", res.hasNext());

        response.put("code", 0);
        response.put("data", data);

        return ResponseEntity.ok(response);
    }

    // 获取详情
    @GetMapping("/get/{user_id}")
    public ResponseEntity<Map<String, Object>> get(@PathVariable Long user_id) {
        try {
            Map<String, Object> response = new HashMap<>();
            User res = Repository.findById(user_id).orElse(null);
            if (res != null) {
                response.put("status", 0);
                response.put("msg", "success");
                response.put("data", res);
            } else {
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("userId", user_id);
                errorData.put("suggestion", "请检查用户user_id是否正确");
                throw new BusinessException("用户不存在", errorData);
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 或者直接抛出带数据的运行时异常
            Map<String, Object> errorContext = new HashMap<>();
            errorContext.put("userId", user_id);
            errorContext.put("method", "GET");
            throw new RuntimeException("获取用户信息失败: " + e.getMessage());
        } finally {
            System.out.println("finally block");
        }
    }




    // 添加
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> add(@RequestBody User data) {
        Map<String, Object> response = new HashMap<>();
        User res = Repository.save(data);
        response.put("status", 0);
        response.put("msg", "操作成功");
        response.put("data", res);
        return ResponseEntity.ok(response);
    }

    // 修改
    @PutMapping("/update/{id}")
    public ResponseEntity<Map<String, Object>> update(@PathVariable Long id, @RequestBody User model) {
        Map<String, Object> response = new HashMap<>();
        if (Repository.existsById(id)) {
            model.setId(id);
            User res = Repository.save(model);
            response.put("status", 0);
            response.put("msg", "操作成功");
            response.put("data", res);
        } else {
            response.put("status", 1);
            response.put("msg", "数据不存在");
        }
        return ResponseEntity.ok(response);
    }


}
